﻿using MediatR;
using U.B.DoMain;
using U.B.ErrorCode;
using U.B.Repistory;
using U.B.WriteApi.Command;

namespace U.B.WriteApi.CommandHander
{
    public class DelMenuCommandHander : IRequestHandler<DelMenuCommand, ApiResult<object>>
    {
        private readonly IRepistory<Menu> Menurepistory;
         public DelMenuCommandHander(IRepistory<Menu> Menurepistory)
        {
            this.Menurepistory = Menurepistory;
        }

        public async Task<ApiResult<object>> Handle(DelMenuCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result = new ApiResult<object>();
            //1.查询当前对象 及 父级下的所有子子级
            var list = Menurepistory.GetAll().Where(x => x.IsDeleted == false).ToList();
            //2.递归查询
            var menulist = GetMenuList(list, request.MenuId);
            //3,.查询到删除
            var res = "";
            //4.当前修改
            var getmenu = Menurepistory.GetAll().FirstOrDefault(x => x.MenuId == request.MenuId);
            getmenu.IsDeleted = true;
            res = Menurepistory.Update(getmenu).ToString();
            foreach (var item in menulist)
            {
                item.IsDeleted = true;
                res = Menurepistory.Update(item).ToString();
            }
            result.code = Renum.删除成功;
            result.Message=Renum.删除成功.ToString();
            result.Data = res;
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 递归查询
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public IEnumerable<Menu> GetMenuList(List<Menu> menus, int MenuId)
        {
            var children = menus.Where(x => x.PId == MenuId);
            foreach (var item in children)
            {
                yield return item;
                var subChildren = GetMenuList(menus, item.MenuId);
                foreach (var subItem in subChildren)
                {
                    yield return subItem;
                }
            }
        }
    }
}
